package com.example.demo.config;

import com.example.demo.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

//设置登录拦截器
@Component
public class  LoginInterCeptor implements HandlerInterceptor {

    @Autowired
    private static Logger log = LoggerFactory.getLogger(LoginInterCeptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //验证token是否合法
        String user_token_header =  request.getHeader("user_token_header"); //从前端传来的Header中获取JWT令牌
        log.info("从header中获取信息,token:"+user_token_header);
        Claims claims = JwtUtils.verify(user_token_header);
        if(claims == null) //如果JWT令牌为null就要返回401,前端通过401就要跳转到登录界面
        {
            log.error("拦截器 token校验失败");
            response.setStatus(401);
            return false;
        }
        return true;
    }

}
